package com.huohuzhihui.web.controller.api;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.huohuzhihui.account.domain.AccUserAccount;
import com.huohuzhihui.account.service.IAccUserAccountService;
import com.huohuzhihui.account.service.impl.AccUserAccountServiceImpl;
import com.huohuzhihui.common.core.controller.BaseController;
import com.huohuzhihui.common.core.domain.AjaxResult;
import com.huohuzhihui.common.core.domain.entity.SysUser;
import com.huohuzhihui.common.core.domain.model.LoginUser;
import com.huohuzhihui.common.utils.SecurityUtils;
import com.huohuzhihui.common.utils.SmsVerificationCodeService;
import com.huohuzhihui.framework.web.service.TokenService;
import com.huohuzhihui.wxminiapp.domain.WxLoginRequest;
import com.huohuzhihui.wxminiapp.service.WxService;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *微信api
 * 
 * @author lizhihe
 * @date 2020-11-22
 */
@RestController
@RequestMapping("/api/wx")
public class ApiWxController extends BaseController
{

    @Autowired
    private WxService wxService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IAccUserAccountService iAccUserAccountService;
    @Autowired
    private SmsVerificationCodeService smsVerificationCodeService;

    private String appId = "wx06f2d3b0846b0128";

    /**
     * 登录方法
     *
     * @param request 登录信息
     * @return 结果
     */
    @PostMapping("/loginByMobile")
    public AjaxResult loginByMobile(@RequestBody WxLoginRequest request) {
        AjaxResult ajax = AjaxResult.success();
        String token = null;
        try {
            // 生成令牌
            token = wxService.loginByPhonenumber(request.getMobile());
            ajax.put("data", token);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return ajax;
    }

    @RequestMapping("/getUserInfo")
    public AjaxResult getUserInfo(@RequestParam(name = "code") String code) throws Exception {
        if (StringUtils.isBlank(code)) {
            AjaxResult ajax = AjaxResult.error("code不能为空！");
            return ajax;
        }
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxService.getUserInfo(code);
        if(wxMaJscode2SessionResult==null){
            AjaxResult ajax = AjaxResult.error("获取微信用户session错误，请确认微信相关配置参数是否正确！");
            return ajax;
        }
        return new AjaxResult(200, "获取微信用户session成功", wxMaJscode2SessionResult);
    }
    @PostMapping("/getUserAccount")
    public AjaxResult getUserAccount(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser sysUser = loginUser.getUser();
        AccUserAccount accUserAccount = iAccUserAccountService.selectAccUserAccountByUserId(sysUser.getUserId());
        AjaxResult ajax = AjaxResult.success(accUserAccount);
        return  ajax;
    }


    @PostMapping("/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestBody WxLoginRequest wxLoginRequest) {
        String phonenumber = wxService.getPhone( wxLoginRequest.getOpenId(),wxLoginRequest.getSessionKey(),wxLoginRequest.getEncryptedData(),wxLoginRequest.getIv());
        return new AjaxResult(200, "获取微信绑定手机号成功", phonenumber);
    }


    /**
     * 微信消息接收和token验证
     */
    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public String get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("----------------验证微信服务号信息开始----------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败


        if (wxService.checkSignature(signature, timestamp, nonce,appId)) {
            System.out.println("----验证服务号结束.........");
            return echostr;
        }else{
            return null;
        }
    }//p


    /**
     * 获取微信JS-SDK签名
     */
    @RequestMapping(value = "/getWeixinJsConfig", method = RequestMethod.POST)
    public AjaxResult getWeixinJsConfig(String appId,String signUrl) throws Exception {
        try{
            return new AjaxResult(200, "获取微信JS-SDK签名成功", wxService.getWeixinJsConfig(appId,signUrl));

        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }//p

}
